package com.example.secondhandshop.model;

import com.example.secondhandshop.bean.Item;
import com.example.secondhandshop.bean.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ProductService {
    private static final String ADD_PRODUCT_URL = "https://api-store.openguet.cn/api/member/tran/goods/add";
    private static final String APP_ID = "2de64479320b423cbc05dd7e6c922999";
    private static final String APP_SECRET = "16786e5aa3e8a7f8e4f24940cb351fad802ca";

    public void addProduct(Item item, ProductCallback callback) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();
            Gson gson = new Gson();
            String json = gson.toJson(item);

            RequestBody body = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    json.getBytes(StandardCharsets.UTF_8)
            );

            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json")
                    .add("appId", APP_ID)
                    .add("appSecret", APP_SECRET)
                    .add("Content-Type", "application/json")
                    .build();

            Request request = new Request.Builder()
                    .url(ADD_PRODUCT_URL)
                    .headers(headers)
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    callback.onProductAddFailure("网络请求失败: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseString = response.body().string();
                    ResponseBody<Object> responseBody = new Gson().fromJson(responseString, new TypeToken<ResponseBody<Object>>(){}.getType());
                    if (responseBody.getCode() == 200) {
                        callback.onProductAdded(responseBody.getMsg());
                    } else {
                        callback.onProductAddFailure(responseBody.getMsg());
                    }
                }
            });
        }).start();
    }

    public interface ProductCallback {
        void onProductAdded(String message);
        void onProductAddFailure(String error);
    }
}